// 云函数入口文件
const cloud = require('wx-server-sdk')

cloud.init({
  env: cloud.DYNAMIC_CURRENT_ENV
})

const db = cloud.database()
const _ = db.command

/**
 * 手机验证码校验
 */
exports.main = async (event, context) => {
  const { OPENID } = cloud.getWXContext()
  const { phone, code } = event
  const now = Date.now()
  const result = await checkCode(phone, code, now)
  if (result.code === 0) {
    const queryResult = await db.collection('user')
      .where({ _openid: OPENID })
      .get()
    if (queryResult.data.length > 0) {
      // 更新用户手机号码
      await db.collection('user')
        .where({ _openid: OPENID })
        .update({ data: { phone } })
    } else {
      // 保存用户信息 - 手机号码
      await db.collection('user')
        .add({
          data: {
            _openid: OPENID,
            create: now,
            phone
          }
        })
    }
  }

  return result
}

/**
 * 验证手机号和验证码
 * @param {String} phone 
 * @param {String} code 
 * @param {Number} now 
 * @returns {Object} 验证结构
 */
async function checkCode (phone, code, now) {
  const time = now - 60 * 60 * 1000
  const res = await db.collection('sent_code')
    .where({
      phone,
      code,
      create: _.gt(time)
    })
    .orderBy('create', 'desc')
    .get()
  const message = res.data[0]
  if (message) {
    if (message.create < (now - 120 * 1000)) {
      return { code: -1, message: '验证码已失效！' }
    } else {
      return { code: 0, message: '验证成功！' }
    }
  } else {
    return { code: -1, message: '验证码错误！' }
  }
}